from threading import Thread
from GetHostIP import HostIP
import socket


class SConnector(object):
    def __init__(self, host, dest):
        self.ip = host[0]
        self.port = host[1]
        self.dest_ip = dest[0]
        self. dest_port = dest[1]
        self.udpSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udpSocket.bind((self.ip, self.port))
        self.addr = ''
        self.data = ''

    def send_data(self):
        while True:
            print("\n")
            data = input("Please enter your msg to send:>>")
            self.udpSocket.sendto(data.encode("gb2312"), (self.dest_ip, self.dest_port))

    def recv_data(self):
        while True:
            rec_info = self.udpSocket.recvfrom(1024)
            self.addr = rec_info[1]
            self.data = rec_info[0].decode("gb2312")
            print("\n[{}]>>{}\n".format(self.addr,  self.data))


if __name__ == "__main__":
    ip = HostIP().ip
    host_port = int(input("Host p:"))
    dest_port = int(input("Destination port:"))
    s = SConnector((ip, host_port), (ip, dest_port))
    tr = Thread(target=s.recv_data)
    ts = Thread(target=s.send_data)
    tr.start()
    ts.start()
    tr.join()
    ts.join()